<template>
  <!-- 头像 -->
  <img class="w-34px h-34px rounded-full select-none" :src="avatar" alt="avatar" />
  <el-dropdown class="m-l-10px" :hide-on-click="false" @command="handleCommand">
    <div class="koi-dropdown">
      {{ userName }}
      <el-icon><arrow-down /></el-icon>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="koiMine">个人中心</el-dropdown-item>
        <el-dropdown-item command="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { koiSessionStorage, koiLocalStorage } from "@/utils/storage.ts";
import { LOGIN_URL } from "@/config";
import { useRouter } from "vue-router";
import { koiLogout } from '@/api/system/login/index.ts'
import { koiNoticeSuccess, koiNoticeError } from "@/utils/koi";
import useAuthStore from "@/stores/modules/auth.ts";

const authStore = useAuthStore();
const router = useRouter();

onMounted(() => {
  handleLoginUser();
})

// 获取用户姓名
const userName = ref();
// 用户头像
const avatar = ref();
const handleLoginUser = () => {
  userName.value = authStore.loginUser.userName || '无名小辈';
  avatar.value = authStore.loginUser.avatar  || 'https://pic4.zhimg.com/v2-702a23ebb518199355099df77a3cfe07_b.webp';
}

// 退出登录
const handleLayout = async () => {
  try {
    await koiLogout();
    koiNoticeSuccess("退出登录成功🌻")
  } catch (error) {
    console.log(error);
    koiNoticeError("退出登录失败🌻")
  }
  koiSessionStorage.clear();
  koiLocalStorage.clear();
  // 必须使用这个把页面缓存刷掉
  window.location.replace(LOGIN_URL);
};

// 下拉折叠
const handleCommand = (command: string | number) => {
  switch (command) {
    case "koiMine":
      router.push("/system/personage");
      break;
    case "logout":
      handleLayout();
      break;
  }
};
</script>

<style lang="scss" scoped>
// dropdown字体颜色
.koi-dropdown {
  color: var(--el-color-primary);
  white-space: nowrap; /* 不换行 */
  cursor: pointer;
  outline: none; // 去除伪元素
}
</style>
